package main 

import (
	"fmt"
	"net"
	"os"
	"alex/ptp1588boundaryclock/com"
	"alex/ptp1588boundaryclock/com/general"
)

func main() {
	fmt.Println("test")
	fmt.Println("Starting UDP-Echo-Server...")
	service := ":1201"
	
	udpAddr, err := net.ResolveUDPAddr("udp", service)
	checkError(err)
	
	conn, err := net.ListenUDP("udp", udpAddr)
	checkError(err)
	
	for {
		handleClient(conn)
	}
}

func handleClient(conn *net.UDPConn) {
	var buff [512]byte
	
	n, _, err := conn.ReadFromUDP(buff[0:])
	
	if err == nil {
		checkBytes(buff[:n])
	} else {
		fmt.Println(err)
	}

	//fmt.Printf("Received: %+v", string(buff[0:n]))
	fmt.Printf("Received %v Bytes: %+v\n", n,  buff[0:n])
/*	_, err2 := conn.WriteToUDP(([]byte)(buff[0:n]), addr)
	if err2 != nil {
		return
	}*/
}

func checkBytes (msg []byte) {
	fmt.Println("Checking Bytes...")
	if len(msg) > 43 && len(msg) < 65 {
		header := new(com.Header)
		header.Init()
		if header.Read(msg[0:34], uint16(len(msg))) {
			fmt.Println("Header Read true!")
			fmt.Println("Entering Announce...")
			var msgText com.Message
			if header.MsgType == com.Announce {
				msgText = &general.AnnounceMessage{}
			}
			msgText.Init()
			if msgText.Read(msg[34:], uint16(0)) {
				fmt.Println("Done reading Announce")
			} else {
				fmt.Println("Error @ Announce")
			}
		} else {
			fmt.Println("Header false!")
		}
	} else {
		fmt.Printf("Msg Length not right: %+v", len(msg))
	}
}



func checkError (err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error")
		os.Exit(1)
	}
}
